package com.example.servletdemo.filter.login;

import com.alibaba.fastjson.JSON;
import com.example.servletdemo.model.User;
import redis.clients.jedis.Jedis;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.UUID;

//@WebFilter(filterName = "LoginFilter",urlPatterns = "/*")
public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
//        System.out.println("TestFilter:doFilter");
        //1.强制转换
        HttpServletRequest request =(HttpServletRequest) servletRequest;
        HttpServletResponse response =(HttpServletResponse) servletResponse;

        String uri = request.getRequestURI();

        if (uri.equals("/loginAuth/login2.html")||uri.equals("/UserLogin2Servlet")){
            filterChain.doFilter(servletRequest, servletResponse);
        }else {
//            User use= (User) request.getSession().getAttribute("user");
            //获取浏览器Cookie
            String token = getCookie("token", request);
            //验证redis
            Jedis jedis = new Jedis("127.0.0.1", 6379);
            jedis.auth("888888");
//            jedis.setex(token,60*30,JSON.toJSONString(user));
            String redis_token = jedis.get(token);
            if(redis_token!=null){
                //重置redis时间
                jedis.expire(token, 30);
                jedis.close();
                filterChain.doFilter(servletRequest, servletResponse);
            }else{
                //没有登录
//                request.getRequestDispatcher("/login.jsp").forward(servletRequest,servletResponse);
                //重定向
                response.sendRedirect("/loginAuth/login2.html");
            }
        }
    }

    @Override
    public void destroy() {
        System.out.println("TestFilter:destroy");
    }

    /**
     * 查找特定cookie值
     *
     * @param cookieName
     * @param request
     * @return
     */
    public static String getCookie(String cookieName, HttpServletRequest request) {
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals(cookieName)) {
                    return cookie.getValue();
                }
            }
        }
        return null;
    }
}
